import { Ref, ref } from "vue";
import { findIndexByLabel, isEmpty, mergeObjects } from ".";
import { ElLoading } from "element-plus";
import request from "./request";
import { UserFilled } from "@element-plus/icons-vue";
import { getShipments } from "../api/shipmentAPI";

export const useMaving = () => {
	const mavingIndex = ref(-1);
	const onStart = (event : { oldIndex : number }) => {
		mavingIndex.value = event.oldIndex;
	}

	const onEnd = (event : { newIndex : number; oldIndex : number }) => {
		console.log('onEnd-event--->', event);
		mavingIndex.value = -1;
	}
	//
	return {
		mavingIndex,
		onStart,
		onEnd
	}
}
export const useSelect = () => {
	// * * * * * ! ! ! qwsc
	const handSelectChange = (formData : Ref<any>, typeList : Array<any>, value : Array<any> | any, type : string, key ?: number) => {
		// 清空并设置新的值
		const setValue = (arr : any, val : string | number) => {
			arr[type] = [];
			arr[type] = [val];
		};
		// 根据类型处理索引和ID
		const handleType = (option : any, indexVar : Ref<number>, idVar : any, blurFunc : Ref<any>) => {
			const index = findIndexByLabel(option.value, value1[0], 'value');
			indexVar.value = index;
			formData.value[idVar] = value1[0];
			blurFunc.value.blur();
		};
		let value1 = [value[value.length - 1]];
		if (isEmpty(value1[0])) {
			value1 = [];
		} else {
			value1 = [value1[0]];
		}
		setValue(formData.value, value1[0]);
		//
		typeList.forEach((item : any) => {
			if (type === item.type && !key) {
				handleType(item.option, item.indexVar, item.idVar, item.blurRef);
				if (item?.fun) {
					item.fun(value1[0], key);
				}
			}
			//
			if (type === item.type && key) {
				// console.log('key--->', key);
				const index = findIndexByLabel(item.option, value1[0], 'value');
				item.indexVar.value = index;
				setValue(item.tableData.value[key], value1[0]);
				item.tableData.value[key][item.idVar] = value1[0];
				if (item?.fun) {
					item.fun(value1[0], key);
				}
				item.blurRef.value.blur();
			}
		});
		return {
			handleType
		};
	};
	//
	return {
		handSelectChange
	};
};

export const useDialog = () => {
	// 定义 useDialog 的逻辑
};

export const formatTableData = async (tableData : Array<any>, typeId : string, type : string, shipmentType : string = 'shipment_status', resultType : string = 'tag') => {
	//调用数据字典接口
	const data = await getShipments(shipmentType, resultType);
	//
	tableData.forEach((item : any, key : number) => {
		//
		data.forEach((item1 : any, key1 : number) => {
			const typeIds = typeId.split('.');
			if (typeIds.length === 1) {
				if (item[typeId] === item1.value) {
					item[type] = item1;
				}
			}
			if (typeIds.length === 2) {
				if (item[typeIds[0]][typeIds[1]] === item1.value) {
					item[type] = item1;
				}
			}
		});
	});
	//
	// console.log('tableData --->',tableData);
}